<template>
  <el-dialog v-model="templatesSort" title="算子排序" width="500" :show-close="false">
    <el-table class="tableContent" ref="dragTable" :data="labelAssignData.results" border
      style="width: 100%;font-size: 12px;" :header-cell-style="{ color: '#333333', textAlign: 'left' }" row-key="id">
      <el-table-column align="center" prop="id" label="" width=" 80">
        <template #default>
          <div class="changeSort">
            <el-icon>
              <Switch />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="label" label="模板名称" />
      <template #empty>
        <div class="noData">暂无数据</div>
      </template>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm(false)">取消</el-button>
        <el-button type="primary" @click="sortSet()">
          修改
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, shallowRef, watch, onMounted, reactive, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { getTemplates, patchSequences } from 'src/api/designerTool'
import Sortable from "sortablejs";
import { ElMessage, ElMessageBox } from 'element-plus';
import { time } from 'console';
const router = useRouter()
const projectId = router.currentRoute.value.params.project_id

// eslint-disable-next-line vue/no-dupe-keys
const templatesSort = ref(false)
const labelAssignData = shallowRef(
  {
    count: 0,
    next: "",
    previous: "",
    results: []
  }
)
const props = defineProps({
  category_id: {
    type: Number
  },
  templatesSort: {
    type: Boolean
  },
})
const template_ids = ref(<any>[])

watch(() => props.templatesSort, (newData, oldData) => {
  templatesSort.value = newData
  if (newData) {
    templatesData()
    nextTick(() => {
      initSort('tableContent')
    })
  }

})
const emits = defineEmits(['emitsFun'])
function resetForm(sortState:boolean) {
  emits('emitsFun', sortState)
}

//获取算子模板信息列表
function templatesData() {
  let obj = {
    ordering:'sequence'
  }
  if (props.category_id != 0) {
    obj.category_id = props.category_id
  } else {
    delete obj.category_id
  }
  getTemplates(projectId, obj).then((res: any) => {
    labelAssignData.value = res.data
    template_ids.value = templateFilter(labelAssignData.value.results)
  }).catch(error => {
    console.log(error)
  })
}
// 获取数据id
const templateFilter = (treeData: Array<any>) => {
  let filterArr = treeData.map((item, index) => {
    return item.id
  })
  return filterArr
}
// 创建拖拽实例
const initSort = (className: string) => {
  const table = document.querySelector(`.${className} .el-table__body-wrapper tbody`);
  Sortable.create(table, {
    group: 'shared',
    animation: 150,
    easing: 'cubic-bezier(1, 0, 0, 1)',
    onStart: () => {
      console.log("开始拖动");
    },
    // 结束拖动事件
    onEnd: ({
      newIndex,
      oldIndex
    }: any) => {
      setNodeSort(template_ids.value , oldIndex, newIndex)
    },
  })
}
// 拖拽完成修改数据排序
const setNodeSort = (data: any, oldIndex: any, newIndex: any) => {
  const currRow = data.splice(oldIndex, 1)[0];
  data.splice(newIndex, 0, currRow);
}
function sortSet() {
  ElMessageBox.confirm('确定修改数据排序吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let obj = {
      category_id: props.category_id,
      template_ids: template_ids.value
    }
    patchSequences(projectId, obj).then(() => {
      ElMessage.success('排序成功！')
      resetForm(true)
    }).catch(error => {
      console.log(error)
    })
  })
}


</script>

<style scoped lang="scss">
.changeSort {
  cursor: pointer;

  .el-icon {
    transform: rotateZ(90deg);
    color: #3d5ce4;
    font-size: 14px;
    vertical-align: middle;
  }
}
</style>
